class Solution {
public:
    int maxEnvelopes(vector<vector<int>>& envelopes) {
        sort(envelopes.begin(), envelopes.end(), [&](vector<int>& e1, vector<int>& e2)
        {
            return e1[0] != e2[0] ? e1[0] < e2[0] : e1[1] > e2[1];
        });
        vector<int> ret;
        ret.push_back(envelopes[0][1]);
        for(auto& e : envelopes)
        {
            if(e[1] > ret.back())
            {
                ret.push_back(e[1]);
            }
            else // 二分找到要放的位置（找大于等于e[1]的左端点）
            {
                int left = 0, right = ret.size() - 1;
                while(left < right)
                {
                    int mid = (left + right) >> 1;
                    if(ret[mid] < e[1])
                        left = mid + 1;
                    else
                        right = mid;
                }
                ret[left] = e[1];
            }
        }
        return ret.size();
    }
};